package com.ymx.darling.executor.mapping.metadata;

import com.ymx.darling.type.TypeHandler;
import com.ymx.darling.util.StringUtil;

import java.lang.reflect.Field;
import java.util.Objects;

/**
 * 封装结果集元数据信息
 *
 * @author 爱java的小于
 * @time 2022-10-02
 */
public class MetaData {
    /*在ResultSet中的索引位置*/
    private final int index;

    /*结果集字段类型 此类型为JDBC数据类型数值常量*/
    private final int type;

    /*结果集字段名称*/
    private final String name;

    private final String toString;

    private final int hashCode;
    /**
     *保存table$column中table的值
     */
    private String asTable;

    /*对应类中的字段*/
    private Field field;

    /*结果集类型映射处理器*/
    private TypeHandler<?> typeHandler;

    public MetaData(String columnName, int fieldType, int index){
        this.index = index;
        this.type = fieldType;
        this.toString = columnName;
        this.hashCode = columnName.hashCode();
        if (StringUtil.containsChar(columnName, '$')) {
            String[] split = columnName.split("\\$");
            this.asTable = split[0];
            this.name = split[1];
        } else {
            this.name = columnName;
        }
    }

    public String getName() {
        return name;
    }

    public void setField(Field field) {
        this.field = field;
    }

    public Field getField() {
        return field;
    }

    public int getType() {
        return type;
    }

    public int getIndex() {
        return index;
    }

    public void setTypeHandler(TypeHandler<?> typeHandler) {
        this.typeHandler = typeHandler;
    }

    public TypeHandler<?> getTypeHandler() {
        return typeHandler;
    }

    public boolean hasAsTable() {
        return Objects.nonNull(asTable);
    }

    public String getAsTable() {
        return asTable;
    }

    @Override
    public String toString() {
        return this.toString;
    }

    @Override
    public int hashCode() {
        return this.hashCode;
    }

    @Override
    public boolean equals(Object obj) {
        if (Objects.isNull(obj) || !(obj instanceof MetaData)) {
            return false;
        }
        return obj == this || obj.hashCode() == this.hashCode();
    }
}
